// Fisher-Yates 洗牌算法用于随机抽取元素
function getRandomElements(arr, n) {
  const shuffled = arr.slice();
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled.slice(0, n);
}

// 过滤并随机抽取题目
async function getQuestionsByType(type, arr, count, cateValue) {
  const questions = await questionModel.find({
    belong: { $in: arr }, // 从题库中查找属于 arr 中任一 stage 的问题
    cate: cateValue, // 过滤出指定类型的题目
  });

  return getRandomElements(
    questions.map((q) => q._id),
    count
  );
}

// 主函数
async function getRandomElementsFromData(data) {
  const result = {};

  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      const { arr, count } = data[key];
      let cateValue; // 根据键名确定 cate 值

      switch (key) {
        case "radio":
          cateValue = 1;
          break;
        case "checkbox":
          cateValue = 2;
          break;
        case "judgment":
          cateValue = 3;
          break;
        case "short":
          cateValue = 4;
          break;
        default:
          continue;
      }

      result[key] = await getQuestionsByType(key, arr, count, cateValue);
    }
  }

  return result;
}
